import { datapasss, wxinfolist, power } from "../../../server/api";
import { captureTime } from "../../../server/pulbmethod";
import { debounce } from "../../../server/shake";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    titlename: "",
    types: "",
    id: "",
    obj: {},
    list: [],
    img1: [],
    img2: [],
    val: {},
    iShow: false,
    flag: "",
    typename: "",
    typevalue: "",
    gdname: "",
    showend: false,
    minDate: new Date().getTime(),
    maxDate: new Date(2019, 10, 1).getTime(),
    currentDate: new Date().getTime(),
    time: null,
    score: "0",
    isjf: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options, "op");
    const type = options.type;
    this.setData({
      types: type,
      id: options.id,
      flag: options.flag,
      gdname: options.gdname,
    });
    if (type == 0) {
      this.setData({ titlename: "审批详情" });
    } else if (type == 1) {
      this.setData({ titlename: "抄送详情" });
    } else if (type == 4) {
      this.setData({ titlename: "活动详情" });
    } else {
      this.setData({ titlename: "归档详情" });
    }
  },
  //获取当前时间
  gettime() {
    const date = new Date();
    var year = date.getFullYear();
    var month = ("0" + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的
    var day = ("0" + date.getDate()).slice(-2);
    var hours = ("0" + date.getHours()).slice(-2);
    var minutes = ("0" + date.getMinutes()).slice(-2);
    var Seconds = ("0" + date.getSeconds()).slice(-2);
    const time = year + "-" + month + "-" + day + " " + hours + ":" + minutes;
    return time;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    if (this.data.flag == 1) {
      this.gethddata();
      this.setData({ types: 7 });
    } else if (this.data.flag == 0) {
      this.setData({ types: 8 });
      this.getdetail();
    }
  },

  //活动详情数据
  async gethddata() {
    const params = {
      processCode: this.data.id,
    };
    const res = await wxinfolist(params);
    if (res.code == 200) {
      const arr = [];
      res.result.process.map((item) => {
        arr.push({
          status: item.type,
          name: item.name,
          time: item.dataTime == null ? "" : captureTime(item.dataTime),
          processId: item.processId,
          processCode: item.processCode,
          typeKey: item.typeKey,
          type: item.type,
          processTotal: item.processTotal,
          icon:
            item.type == "发起申请" || item.type == "审核通过"
              ? "../../../icon/管理端/审核过程-通过x160.png"
              : "../../../icon/管理端/审核过程-等待x160.png",
        });
      });
      const { score, outTime } = res.result.application;
      this.setData({
        val: res.result.application,
        score: score == null ? 0 : score,
        list: arr,
        typevalue: arr[arr.length - 1].typeKey,
        time: outTime == null ? "" : outTime,
      });
      this.setData({
        typename: this.data.list[this.data.list.length - 1].type,
      });
      //流程节点的长度
      const lclength = this.data.list.length - 1;
      //获取最后一条total
      const index = this.data.list.length - 1;
      const total = this.data.list[index].processTotal;
      console.log(total == lclength, "////");
      //如果最后一条total等于减去的流程节点的长度就需要出填写积分和时间W
      if (total == lclength) {
        this.setData({ isjf: true });
      }
    }
  },
  //商家详情数据
  async getdetail() {
    const params = {
      processCode: this.data.id,
    };
    const res = await wxinfolist(params);
    if (res.code == 200) {
      const arr = [];
      res.result.process.map((item) => {
        console.log(item.dataTime, "processId");
        arr.push({
          status: item.type,
          name: item.name,
          time: item.dataTime == null ? "" : captureTime(item.dataTime),
          processId: item.processId,
          processCode: item.processCode,
          typeKey: item.typeKey,
          type: item.type,
          processTotal: item.processTotal,
          icon:
            item.type == "发起申请" || item.type == "审核通过"
              ? "../../../icon/管理端/审核过程-通过x160.png"
              : "../../../icon/管理端/审核过程-等待x160.png",
        });
      });
      console.log(res.result, "res");
      this.setData({
        obj:
          res.result.application == null
            ? {}
            : res.result.application.pointsMerchantApplicationDtos[0],
        list: arr,
        typevalue: arr[arr.length - 1].typeKey,
        img1:
          res.result.application == null
            ? ""
            : res.result.application.idPicturePaths,
        img2:
          res.result.application == null
            ? ""
            : res.result.application.shopPicturePaths,
      });
    }
  },
  //查看图片
  bindimg(e) {
    const current = e.currentTarget.dataset.url;
    const urls = this.data.val.picture.map((v) => v);
    wx.previewImage({
      current,
      urls,
    });
  },
  openimg(e){
    const current = e.currentTarget.dataset.url;
    console.log(current,'ccc');
    wx.previewImage({
      current: current, // 当前显示图片的链接，不填则默认为 urls 的第一张
      urls: [current ]// 需要预览的图片链接列表
      })
  },
  onInputend(e) {
    console.log(this.gettime() == this.msToDate(e.detail));
    if (this.msToDate(e.detail) <= this.gettime()) {
      wx.showToast({
        title: "有效时间必须大于当前时间",
        icon: "none",
      });
    } else {
      this.setData({ time: this.msToDate(e.detail), showend: false });
    }
  },
  msToDate(milliseconds) {
    var date = new Date(milliseconds);
    var year = date.getFullYear();
    var month = ("0" + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的
    var day = ("0" + date.getDate()).slice(-2);
    var hours = ("0" + date.getHours()).slice(-2);
    var minutes = ("0" + date.getMinutes()).slice(-2);
    return year + "-" + month + "-" + day + " " + hours + ":" + minutes;
  },
  onClose2() {
    this.setData({ showend: false });
  },
  //选择时间
  iptchange() {
    this.setData({ showend: true });
  },
  //通过
  passed: debounce(async function () {
    if (this.data.flag == 1) {
      if (this.data.score == "" || this.data.score < 0) {
        wx.showToast({
          title: "请填写积分",
          icon: "none",
        });
      } else if (this.data.time == "" || this.data.time == null) {
        wx.showToast({
          title: "积分有效时间不能为空",
          icon: "none",
        });
      } else {
        const p = this.data.list.filter((item) => item.typeKey == "1");
        const params = {
          processCode: p[0].processCode,
        };
        const data = await power(params);
        if (data.code == 200) {
          if (data.result.result == true) {
            const params = {
              processId: p[0].processId,
              outTime: this.data.time,
              score: this.data.score,
            };
            const params1 = {
              processId: p[0].processId,
            };
            const data = await datapasss(
              this.data.types == 8 ? params1 : params
            );

            if (data.code == 200) {
              wx.showToast({
                title: "审批成功",
                icon: "success",
              });
              setTimeout(() => {
                wx.navigateBack(1);
              }, 500);
            }
          } else {
            wx.showToast({
              title: "您已经审批过了！",
            });
          }
        } else {
          wx.showToast({
            title: data.result.message,
          });
        }
      }
    } else {
      const p = this.data.list.filter((item) => item.typeKey == "1");
      const params = {
        processCode: p[0].processCode,
      };
      const data = await power(params);
      if (data.code == 200) {
        if (data.result.result == true) {
          const params = {
            processId: p[0].processId,
            outTime: this.data.time,
            score: this.data.score,
          };
          const params1 = {
            processId: p[0].processId,
          };
          const data = await datapasss(this.data.types == 8 ? params1 : params);

          if (data.code == 200) {
            wx.showToast({
              title: "审批成功",
              icon: "success",
            });
            setTimeout(() => {
              wx.navigateBack(1);
            }, 500);
          }
        } else {
          wx.showToast({
            title: "您已经审批过了！",
          });
        }
      } else {
        wx.showToast({
          title: data.result.message,
        });
      }
    }
  },3000),
  //驳回
  async reject() {
    const p = this.data.list.filter((item) => item.typeKey === 1);
    const params = {
      processCode: p[0].processCode,
    };
    const data = await power(params);
    if (data.code == 200) {
      if (data.result.result == true) {
        const pid = p[0].processId;
        const processCode = p[0].processCode;
        wx.navigateTo({
          url: `../reject/reject?processId=${pid}&processCode=${processCode}`,
        });
      } else {
        wx.showToast({
          title: "您已经审批过了!",
        });
      }
    } else {
      wx.showToast({
        title: data.result.message,
      });
    }
  },
  onChange(e) {
    this.setData({ score: e.detail });
  },
  stepperchange(e) {
    let val = e.detail.value.replace(/(^\s*)|(\s*$)/g, "");
    if (!val) {
      return "";
    }
    var reg = /[^\d.]/g;
    // 只能是数字和小数点，不能是其他输入
    val = val.replace(reg, "");
    // // 保证第一位只能是数字，不能是点
    val = val.replace(/^\./g, "");
    // // 小数只能出现1位
    val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    // // 小数点后面保留2位
    val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3");
    console.log(val);
    return val;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
